﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using WpfSnqkGasAnalysis.IBusiness_impl;
using WpfSnqkGasAnalysis.Model;

namespace WpfSnqkGasAnalysis
{
    /// <summary>
    /// 数据字典。       PageDict.xaml 的交互逻辑
    /// </summary>
    public partial class PageDict : Page
    {
        public PageDict()
        {
            InitializeComponent();
        }

        SourceDictBusiness sourceDictBusiness = new SourceDictBusiness();

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {

            var all = sourceDictBusiness.GetAll();

            //类别
            var list = all.Where(g => g.Group_id.Equals("cate")).ToList();
            this.dgCateGy.DataContext = list;

            //层位
            var listCengWei = all.Where(g => g.Group_id.Equals("cengwei")).ToList();
            dgCengWei.DataContext = listCengWei;

            //构造名称,     //创建时间：2022-12-3 00:04:08
            var dg_structureList = all.Where(g => g.Group_id.Equals("structure")).ToList();
            dg_structure.DataContext = dg_structureList;

            //取样单位。//创建时间：2022-12-3 00:10:03
            var quyangList = all.Where(g => g.Group_id.Equals("quyang")).ToList();
            dg_quyang.DataContext = quyangList;

            //取样地点。//创建时间：2022-12-3 17:48:58
            var dg_quyangAddressList = all.Where(g => g.Group_id.Equals("quyangAddress")).ToList();
            dg_quyangAddress.DataContext = dg_quyangAddressList;

            //取样条件。//创建时间：2022-12-3 17:52:23
            var dg_quyangConditionList = all.Where(g => g.Group_id.Equals("quyangCondition")).ToList();
            dg_quyangCondition.DataContext = dg_quyangConditionList;

            //取样位置。//创建时间：2022-12-3 18:09:53
            var dg_quyangLocationList = all.Where(g => g.Group_id.Equals("quyangLocation")).ToList();
            dg_quyangLocation.DataContext = dg_quyangLocationList;

            //注释时间：2023-1-6 17:15:49
            ////姓名下拉框。//创建时间：2022-12-3 18:14:44
            //var dg_userList = all.Where(g => g.Group_id.Equals("userlist")).ToList();
            //dg_user.DataContext = dg_userList;

            //天然气备注标准   //添加时间：2023-1-11 13:52:17
            var dg_userList = all.Where(g => g.Group_id.Equals("gas_bz_remark_list")).OrderBy(d => d.Createtime).ToList();
            dgGasRemarkList.DataContext = dg_userList;

            //特殊报告备注，标准   //创建时间：2023-1-13 09:58:40。作者:王浩力
            var teshu_report_remarkList = all.Where(g => g.Group_id.Equals(dgTeshu_report_remarkList.Tag.ToString())).OrderBy(d => d.Createtime).ToList();
            dgTeshu_report_remarkList.DataContext = teshu_report_remarkList;

            //有机硫,打印；备注标准；  //创建时间：2023-1-13 13:58:27；作者:王浩力
            var sliu_report_remarkList = all.Where(g => g.Group_id.Equals(dgSliuRemarkList.Tag.ToString())).OrderBy(d => d.Createtime).ToList();
            dgSliuRemarkList.DataContext = sliu_report_remarkList;

            //水露点，打印报告备注    //创建时间：2023-1-31 10:02:24；作者:王浩力
            var water_report_remarkList = all.Where(g => g.Group_id.Equals(dgWaterRemarkList.Tag.ToString())).OrderBy(d => d.Createtime).ToList();
            dgWaterRemarkList.DataContext = water_report_remarkList;
           
            //净化气，打印报告备注    //创建时间：2023-1-31 10:05:41；作者:王浩力
            var clean_report_remarkList = all.Where(g => g.Group_id.Equals(dgCleanRemarkList.Tag.ToString())).OrderBy(d => d.Createtime).ToList();
            dgCleanRemarkList.DataContext = clean_report_remarkList;
            
        }


        //编辑的单元格
        private void dgCateGy_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            var selectedDataGrid = sender as DataGrid;

            //编辑的单元格
            var editInfo = e.EditingElement.DataContext as Source_dict;
            if (editInfo.Id == 0)
            {
                //新增
                if (e.Column.SortMemberPath.Equals("Item_name"))
                {
                    CellAdd(e, selectedDataGrid, editInfo, 1);
                }
                else if (e.Column.SortMemberPath.Equals("Dict_code"))
                {
                    CellAdd(e, selectedDataGrid, editInfo, 2);
                }
            }
            else
            {
                //编辑
                if (e.Column.SortMemberPath.Equals("Item_name"))
                {
                    CellEdit(e, editInfo, 1);
                }
                else if (e.Column.SortMemberPath.Equals("Dict_code"))
                {
                    CellEdit(e, editInfo, 2);
                }

            }
        }

        //编辑单元格。创建时间：2022-12-2 23:54:45。作者：王浩力
        private void CellEdit(DataGridCellEditEndingEventArgs e, Source_dict? editInfo, int column)
        {
            //编辑后的值
            string input = ((System.Windows.Controls.TextBox)e.EditingElement).Text;
            if (string.IsNullOrWhiteSpace(input))
            {
                ShowAlertHelpter.ShowAlert("配置项名称，不允许为空");
                return;
            }
            if (column == 1)
            {
                editInfo.Item_name = input;
            }
            else
            {
                editInfo.Dict_code = input;
            }

            Task.Run(() =>
            {
                var result = sourceDictBusiness.Update(editInfo);
                ShowAlertHelpter.ShowAlert(editInfo.Item_name + "，" + result.Msg);
            });
        }

        //单元格新增一行。创建时间：2022-12-2 23:54:45。作者：王浩力
        private void CellAdd(DataGridCellEditEndingEventArgs e, DataGrid? selectedDataGrid, Source_dict? editInfo, int column)
        {
            //编辑后的值
            string input = ((System.Windows.Controls.TextBox)e.EditingElement).Text;
            if (string.IsNullOrWhiteSpace(input))
            {
                return;
            }
            editInfo.Group_id = selectedDataGrid.Tag.ToString();//根据分组id来
            if (column == 1)
            {
                editInfo.Item_name = input;
            }
            else
            {
                editInfo.Dict_code = input;
            }
            editInfo.D_sort = 9999;
            Task.Run(() =>
            {
                var result = sourceDictBusiness.Add(editInfo);
                if (result.Code == 200)
                {
                    //刷新数据
                    var list = sourceDictBusiness.GetListByGroup(editInfo.Group_id);
                    Dispatcher.Invoke(() =>
                    {
                        selectedDataGrid.ItemsSource = list;
                    });
                }
                ShowAlertHelpter.ShowAlert(result.Msg);
            });
        }


        //右键菜单
        private void dgCateGy_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            var currentDataGrid = sender as DataGrid;
            //var cell = currentDataGrid.CurrentCell;
            //var info = cell.Item as Source_dict;

            ContextMenu contextMenu = new ContextMenu();

            //暂时屏蔽。修改时间：2023-1-13 10:04:37。作者：王浩力
            // MenuItem menuItem = new MenuItem() { Header = "删除此行数据" };
            // menuItem.Click += (s, ce) =>
            //{
            //    var cell = currentDataGrid.CurrentCell;
            //    var info = cell.Item as Source_dict;
            //    Task.Run(() =>
            //    {
            //        var result = sourceDictBusiness.Delete(info);
            //        if (result.Code == 200)
            //        {
            //            var list = currentDataGrid.ItemsSource.Cast<Source_dict>().ToList();
            //            list.Remove(info);
            //            //重新绑定数据
            //            this.Dispatcher.Invoke(() =>
            //            {
            //                currentDataGrid.ItemsSource = list;
            //            });
            //        }
            //        ShowAlertHelpter.ShowAlert(result.Msg );
            //    });
            //};

            //数字大的排在上面
            MenuItem mit = new MenuItem() { Header = "上移" };
            mit.Click += (s, e) =>
            {
                var infoView =
                ((System.Windows.Controls.DataGrid)((System.Windows.Controls.Primitives.Popup)((System.Windows.FrameworkElement)((System.Windows.FrameworkElement)s).Parent).Parent).PlacementTarget).CurrentItem
                as Source_dict;
                if (infoView == null)
                {
                    e.Handled = true;
                    return;
                }
                var dg = ((System.Windows.Controls.DataGrid)((System.Windows.Controls.Primitives.Popup)((System.Windows.FrameworkElement)((System.Windows.FrameworkElement)s).Parent).Parent).PlacementTarget);
                var list = dg.Items.SourceCollection as List<Source_dict>;
                int index = list.IndexOf(infoView);
                if (index == 0)
                {
                    e.Handled = true;
                    return;
                }
                var prev = list[index - 1];
                infoView.D_sort = prev.D_sort + 1;
                Task.Run(() =>
                {
                    var result = sourceDictBusiness.Update(infoView);
                    if (result.Code == (int)ResultCode.Success)
                    {
                        this.Dispatcher.InvokeAsync(() =>
                        {
                            var list = sourceDictBusiness.GetListByGroup(infoView.Group_id);
                            currentDataGrid.ItemsSource = list;
                        });
                    }
                    ShowAlertHelpter.ShowAlert(result.Msg);
                });
            };

            //数字大的排在上面
            MenuItem mit2 = new MenuItem() { Header = "下移" };
            mit2.Click += (s, e) =>
            {
                var infoView =
               ((System.Windows.Controls.DataGrid)((System.Windows.Controls.Primitives.Popup)((System.Windows.FrameworkElement)((System.Windows.FrameworkElement)s).Parent).Parent).PlacementTarget).CurrentItem
               as Source_dict;
                if (infoView == null)
                {
                    e.Handled = true;
                    return;
                }
                var dg = ((System.Windows.Controls.DataGrid)((System.Windows.Controls.Primitives.Popup)((System.Windows.FrameworkElement)((System.Windows.FrameworkElement)s).Parent).Parent).PlacementTarget);
                var list = dg.Items.SourceCollection as List<Source_dict>;
                int index = list.IndexOf(infoView);
                if (index == list.Count - 1)
                {
                    e.Handled = true;
                    return;
                }
                var last = list[index + 1];
                infoView.D_sort = last.D_sort - 1;
                Task.Run(() =>
                {
                    var result = sourceDictBusiness.Update(infoView);
                    if (result.Code == (int)ResultCode.Success)
                    {
                        this.Dispatcher.InvokeAsync(() =>
                        {
                            var list = sourceDictBusiness.GetListByGroup(infoView.Group_id);
                            currentDataGrid.ItemsSource = list;
                        });
                    }
                    ShowAlertHelpter.ShowAlert(result.Msg);
                });
            };

            MenuItem mit3 = new MenuItem() { Header = "置顶" };
            mit3.Click += (s, e) =>
            {
                var infoView =
               ((System.Windows.Controls.DataGrid)((System.Windows.Controls.Primitives.Popup)((System.Windows.FrameworkElement)((System.Windows.FrameworkElement)s).Parent).Parent).PlacementTarget).CurrentItem
               as Source_dict;
                if (infoView == null)
                {
                    e.Handled = true;
                    return;
                }
                var dg = ((System.Windows.Controls.DataGrid)((System.Windows.Controls.Primitives.Popup)((System.Windows.FrameworkElement)((System.Windows.FrameworkElement)s).Parent).Parent).PlacementTarget);
                var list = dg.Items.SourceCollection as List<Source_dict>;
                int index = list.IndexOf(infoView);
                if (index == 0)
                {
                    e.Handled = true;
                    return;
                }
                var first = list[0];
                infoView.D_sort = first.D_sort + 200;
                Task.Run(() =>
                {
                    var result = sourceDictBusiness.Update(infoView);
                    if (result.Code == (int)ResultCode.Success)
                    {
                        this.Dispatcher.InvokeAsync(() =>
                        {
                            var list = sourceDictBusiness.GetListByGroup(infoView.Group_id);
                            currentDataGrid.ItemsSource = list;
                        });
                    }
                    ShowAlertHelpter.ShowAlert(result.Msg);
                });
            };

            contextMenu.Items.Add(mit);
            contextMenu.Items.Add(mit2);
            contextMenu.Items.Add(mit3);
            currentDataGrid.ContextMenu = contextMenu;
        }

        //状态修改
        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show("确认操作？", "警告", MessageBoxButton.OKCancel);
            var info = ((System.Windows.FrameworkElement)sender).DataContext as Source_dict;

            //添加时间：2023-1-11 13:57:08
            if (info == null)
            {
                e.Handled = true;
                return;
            }

            if (result == MessageBoxResult.OK)
            {
                //执行保存
                var checkBox = (e.Source as CheckBox);
                byte selected = 0;
                if (checkBox.IsChecked.HasValue && checkBox.IsChecked.Value)
                {
                    selected = 1;
                }
                Task.Run(() =>
                {
                    var result2 = sourceDictBusiness.UpdateStat(info.Id, selected);
                    if (result2.Code == 500)
                    {
                        Dispatcher.Invoke(() =>
                        {
                            //还原选中状态
                            if (info.D_stat == 1)
                            {
                                (e.Source as CheckBox).IsChecked = true;
                            }
                            else
                            {
                                (e.Source as CheckBox).IsChecked = false;
                            }
                        });
                    }
                    ShowAlertHelpter.ShowAlert(result2.Msg);
                });
            }
            else
            {
                e.Handled = false;

                //还原选中状态
                if (info.D_stat == 1)
                {
                    (e.Source as CheckBox).IsChecked = true;
                }
                else
                {
                    (e.Source as CheckBox).IsChecked = false;
                }
            }
        }


    }
}
